Almost all websites use cookies in one form or another. Cookies are a way of remembering users and their interaction with the site by storing information in the cookie file as key value pairs.
When testing a website with Selenium WebDriver, sometimes it is necessary to handle cookies, such as creating new cookies, updating existing cookies with new information or deleting cookies.
In this webdriver tutorial we look at handling cookies in webdriver. Java code examples of how to create, update and delete cookies using selenium webdriver.
To use any of the cookie handling methods in webdriver, we first need to import the Cookie class. To do that, we use
1 import org.openqa.selenium.Cookie;
RETRIEVE ALL COOKIES
1 2 3 4 //This method gets all the cookies public Set getAllCookies() { return driver.manage().getCookies(); }
RETRIEVE A NAMED COOKIE
1 2 3 4 //This method gets a specified cookie public Cookie getCookieNamed(String name) { return driver.manage().getCookieNamed(name); }
RETRIEVE THE VALUE OF A COOKIE
1 2 3 4 //This method gets the value of a specified cookie public String getValueOfCookieNamed(String name) { return driver.manage().getCookieNamed(name).getValue(); }
ADD A COOKIE
1 2 3 4 5 //This method adds or creates a cookie public void addCookie(String name, String value, String domain, String path, Date expiry) { driver.manage().addCookie( new Cookie(name, value, domain, path, expiry)); }
ADD A SET OF COOKIES
1 2 3 4 5 6 7 8 9 10 11 12 //This method adds set of cookies for a domain public void addCookiesToBrowser(Set cookies, String domain) { for (Cookie c : cookies) { if (c != null) { if (c.getDomain().contains(domain)){ driver.manage().addCookie( new Cookie(name, value, domain, path, expiry)); } } } driver.navigate().refresh(); }
DELETE A SPECIFIC COOKIE
1 2 3 4 //This method deletes a specific cookie public void deleteCookieNamed(String name) { driver.manage().deleteCookieNamed(name); }
DELETE ALL COOKIES
1 2 3 4 //This method deletes all cookies public void deleteAllCookies() { driver.manage().deleteAllCookies(); } |